<template>
	<view class="tabs">
		<scroll-view id="tab-bar" class="scroll-h" :scroll-x="true" :show-scrollbar="false"
			:scroll-into-view="scrollInto">
			<view v-for="(tab,index) in tabBars" :key="tab.id" class="uni-tab-item" :id="tab.id" :data-current="index"
				@click="ontabtap">
				<text class="uni-tab-item-title"
					:class="tabIndex==index ? 'uni-tab-item-title-active' : ''">{{tab.name}}</text>
			</view>
		</scroll-view>
		<view class="line-h"></view>
		<swiper :current="tabIndex" class="swiper-box" style="flex: 1;" :duration="300" @change="ontabchange">
			<swiper-item class="swiper-item" v-for="(tab,index1) in newsList" :key="index1">
				<!-- #ifdef APP-NVUE -->
				<list class="scroll-v list" enableBackToTop="true" scroll-y loadmoreoffset="15"
					@loadmore="loadMore(index1)">
					<refresh class="refresh" @refresh="onrefresh(index1)" @pullingdown="onpullingdown"
						:display="tab.refreshing ? 'show' : 'hide'">
						<div class="refresh-view">
							<image class="refresh-icon" :src="refreshIcon"
								:style="{width: (tab.refreshing || pulling) ? 0: '30px'}"
								:class="{'refresh-icon-active': tab.refreshFlag}"></image>
							<loading-indicator class="loading-icon" animating="true"
								v-if="tab.refreshing"></loading-indicator>
							<text class="loading-text">{{tab.refreshText}}</text>
						</div>
					</refresh>
					<cell v-for="(newsitem,index2) in tab.data" :key="index1 + index2">
						<media-item :options="newsitem" @close="close(index1,index2)"
							@click="goDetail(newsitem)"></media-item>
					</cell>
					<cell class="loading-more" v-if="tab.isLoading || tab.data.length > 4">
						<text class="loading-more-text">{{tab.loadingText}}</text>
					</cell>
				</list>
				<!-- #endif -->
				<!-- #ifndef APP-NVUE -->
				<scroll-view class="scroll-v list" enableBackToTop="true" scroll-y @scrolltolower="loadMore(index1)">
					<view v-for="(newsitem,index2) in tab.data" :key="index2">
						<media-item :options="newsitem" @close="close(index1,index2)"
							@click="goDetail(newsitem)"></media-item>
					</view>
					<view class="loading-more" v-if="tab.isLoading || tab.data.length > 4">
						<text class="loading-more-text">{{tab.loadingText}}</text>
					</view>
				</scroll-view>
				<!-- #endif -->
			</swiper-item>
		</swiper>
	</view>
</template>
<script>
	import {
		getLabelList
	} from '@/api/info/label.js'
	import {
		getInfoList
	} from '@/api/info/article.js'
	import {
		getDictDataList
	} from '@/api/system/dict.js'
	import config from '@/config'
	import mediaItem from './news-item.nvue';

	// 缓存每页最多
	const MAX_CACHE_DATA = 100;
	// 缓存页签数量
	const MAX_CACHE_PAGE = 3;

	export default {
		components: {
			mediaItem
		},
		data() {
			return {
				newsList: [],
				cacheTab: [],
				tabIndex: 0,
				tabBars: [],
				scrollInto: "",
				showTips: false,
				navigateFlag: false,
				pulling: false,
				classifyMap:[],
				dictQuery: {
					pageNum: 1,
					pageSize: 100,
					dictType: "article_type"
				},
				refreshIcon: ""
			}
		},
		onLoad() {
			this.tabBars.push({
				"id": "all",
				"name": "全部"
			});
			var that = this;
			getDictDataList(that.dictQuery).then(response => {
				console.info(response);
				this.classifyMap = new Map();
				response.rows.forEach(item => {
					this.tabBars.push({
						"id": item.dictValue,
						"name": item.dictLabel
					});
					this.classifyMap.set(item.dictValue,item.dictLabel);
				});
			});
			setTimeout(() => {
				this.tabBars.forEach((tabBar) => {
					this.newsList.push({
						data: [],
						isLoading: false,
						pageIndex: 1,
						refreshText: "刷新中",
						loadingText: '加载更多...'
					});
				});
				this.getList(0);
			}, 350)
		},
		methods: {
			getList(index) {
				let activeTab = this.newsList[index];
				let classify = this.tabBars[index].id;
				let pageNum = activeTab.pageIndex;
				let pageSize = 10;
				let that = this;
				this.newsList[index].pageIndex = pageNum + 1;
				if(that.newsList[index].isLoading){
					return;
				}
				let query = {
					pageNum: pageNum,
					pageSize: pageSize,
					classify: classify
				};
				getInfoList(query).then(response => {
					if(pageNum * pageSize >= response.total){
						that.newsList[index].isLoading = true;
						that.newsList[index].loadingText = "End~";
					}
					let list = [];
					console.log("----response.rows")
					console.log(response.rows)
					for (let i = 0; i < response.rows.length; i++) {
						let temp = response.rows[i];
						console.log("----response.rows.temp")
						console.log(temp)
						//let classifyName = that.classifyMap.get(temp.classify);
						let item = {
							"articleId": temp.articleId,
							"createTime": temp.createTime,
							"authorName": temp.authorName,
							"authorNickName": temp.authorNickName,
							"authorAvatar": temp.authorAvatar,
							"mode": temp.mode,
							"title": temp.title,
							"classify": temp.classify,
							"sourceName":temp.sourceName,
							"browseCount": temp.browseCount,
							"thumbsUpCount": temp.thumbsUpCount,
							"commentsCount": temp.commentsCount
						};
						if (response.rows[i].cover) {
							if (response.rows[i].cover.indexOf(',') > 1) {
								let strs = response.rows[i].cover.split(",");
								item.coverlist = [];
								for (var j = 0; j < strs.length; j++) {
									let coverUrl = config.baseUrl + strs[j];
									item.coverlist.push({
										"url": coverUrl,
										"width": 641,
										"height": 360
									});
								}
								console.log("----item.coverlist[0]")
								console.log(item.coverlist[0])
								item.topcover = item.coverlist[0].url;
							} else {
								item.cover = config.baseUrl + response.rows[i].cover;
								item.topcover = item.cover;
							}
						}
						item.authorAvatar = config.baseUrl + response.rows[i].authorAvatar;
						list.push(item);
					}
					
					console.log("----list")
					console.log(list)
					activeTab.data = activeTab.data.concat(list);
				});
			},
			goDetail(e) {
				if (this.navigateFlag) {
					return;
				}
				this.navigateFlag = true;
				let item = {
					"articleId": e.articleId,
					"createTime": e.createTime,
					"authorName": e.authorName,
					"authorNickName": e.authorNickName,
					"authorAvatar": e.authorAvatar,
					"mode": e.mode,
					"title": e.title,
					"classify": e.classify,
					"sourceName": e.sourceName,
					"browseCount": e.browseCount,
					"thumbsUpCount": e.thumbsUpCount,
					"commentsCount": e.commentsCount,
					"cover":e.topcover
				};
				let payload = encodeURIComponent(JSON.stringify(item));
				uni.navigateTo({
					//url: '/pages/info/list2detail-detail/list2detail-detail?payload=' + payload
					url: '/pages/info/article-detail/article-detail?payload=' + payload
				});
				setTimeout(() => {
					this.navigateFlag = false;
				}, 200)
			},
			close(index1, index2) {
				uni.showModal({
					content: '是否删除本条信息？',
					success: (res) => {
						if (res.confirm) {
							this.newsList[index1].data.splice(index2, 1);
						}
					}
				})
			},
			loadMore(e) {
				setTimeout(() => {
					this.getList(this.tabIndex);
				}, 2000)
			},
			ontabtap(e) {
				let index = e.target.dataset.current || e.currentTarget.dataset.current;
				this.switchTab(index);
			},
			ontabchange(e) {
				let index = e.target.current || e.detail.current;
				this.switchTab(index);
			},
			switchTab(index) {

				if (this.tabIndex === index) {
					return;
				}
				if (this.newsList[index].data.length === 0) {
					this.getList(index);
				}

				// 缓存 tabId
				if (this.newsList[this.tabIndex].data.length > MAX_CACHE_DATA) {
					let isExist = this.cacheTab.indexOf(this.tabIndex);
					if (isExist < 0) {
						this.cacheTab.push(this.tabIndex);
						//console.log("cache index:: " + this.tabIndex);
					}
				}

				this.tabIndex = index;
				this.scrollInto = this.tabBars[index].id;

				// 释放 tabId
				if (this.cacheTab.length > MAX_CACHE_PAGE) {
					let cacheIndex = this.cacheTab[0];
					this.clearTabData(cacheIndex);
					this.cacheTab.splice(0, 1);
				}
			},
			clearTabData(e) {
				this.newsList[e].data.length = 0;
				this.newsList[e].loadingText = "加载更多...";
			},
			refreshData() {},
			onrefresh(e) {
				var tab = this.newsList[this.tabIndex];
				if (!tab.refreshFlag) {
					return;
				}
				tab.refreshing = true;
				tab.refreshText = "正在刷新...";

				setTimeout(() => {
					this.refreshData();
					this.pulling = true;
					tab.refreshing = false;
					tab.refreshFlag = false;
					tab.refreshText = "已刷新";
					setTimeout(() => { // TODO fix ios和Android 动画时间相反问题
						this.pulling = false;
					}, 500);
				}, 2000);
			},
			onpullingdown(e) {
				var tab = this.newsList[this.tabIndex];
				console.log('-----onpullingdown')
				console.log('-----onpullingdown')
				if (tab.refreshing || this.pulling) {
					return;
				}
				if (Math.abs(e.pullingDistance) > Math.abs(e.viewHeight)) {
					tab.refreshFlag = true;
					tab.refreshText = "释放立即刷新";
				} else {
					tab.refreshFlag = false;
					tab.refreshText = "下拉可以刷新";
				}
			}
		}
	}
</script>

<style>

	page {
		width: 100%;
		min-height: 100%;
		display: flex;
		overflow: hidden;
	}


	#tab-bar {
		border-bottom: 0.1px #ebebeb solid;
	}
	.pages-info-info {
		overflow: hidden;
	}

	.tabs {
		flex: 1;
		flex-direction: column;
		overflow: hidden;
		background-color: #ffffff;
		/* #ifndef APP-PLUS */
		height: 100vh;
		/* #endif */
	}

	.scroll-h {
		position: fixed;
		z-index: 99;
		background-color: #fff;
		width: 750rpx;
		height: 80rpx;
		flex-direction: row;
		flex-wrap: nowrap;
		white-space: nowrap;
		border-color: #cccccc;
		border-bottom-style: solid;
		border-bottom-width: 1px;
	}

	.line-h {
		height: 1rpx;
		background-color: #cccccc;
	}

	.uni-tab-item {
		display: inline-block;
		flex-wrap: nowrap;
		padding-left: 34rpx;
		padding-right: 34rpx;
	}

	.uni-tab-item-title {
		color: #555;
		font-size: 30rpx;
		height: 80rpx;
		line-height: 80rpx;
		flex-wrap: nowrap;
		white-space: nowrap;
	}

	.uni-tab-item-title-active {
		color: #007AFF;
	}

	.swiper-box {
		height: 100%;
		flex: 1;
	}

	.swiper-item {
		flex: 1;
		flex-direction: row;
	}

	.scroll-v {
		flex: 1;
		/* #ifndef MP-ALIPAY */
		flex-direction: column;
		/* #endif */
		width: 750rpx;
		width: 100%;
	}

	.update-tips {
		position: absolute;
		left: 0;
		top: 41px;
		right: 0;
		padding-top: 5px;
		padding-bottom: 5px;
		background-color: #FDDD9B;
		align-items: center;
		justify-content: center;
		text-align: center;
	}

	.update-tips-text {
		font-size: 14px;
		color: #ffffff;
	}

	.refresh {
		width: 750rpx;
		width: 100%;
		height: 64px;
		justify-content: center;
	}

	.refresh-view {
		flex-direction: row;
		flex-wrap: nowrap;
		align-items: center;
		justify-content: center;
	}

	.refresh-icon {
		width: 30px;
		height: 30px;
		transition-duration: .5s;
		transition-property: transform;
		transform: rotate(0deg);
		transform-origin: 15px 15px;
	}

	.refresh-icon-active {
		transform: rotate(180deg);
	}

	.loading-icon {
		width: 20px;
		height: 20px;
		margin-right: 5px;
		color: #999999;
	}

	.loading-text {
		margin-left: 2px;
		font-size: 16px;
		color: #999999;
	}

	.loading-more {
		align-items: center;
		justify-content: center;
		padding-top: 10px;
		padding-bottom: 10px;
		text-align: center;
	}

	.loading-more-text {
		font-size: 28rpx;
		color: #999;
	}

	.scroll-v {
		height: calc(100vh - 44.5px);
	}

	.swiper-box {
		height: calc(100vh - 44.5px);
		margin-top: 44.5px;
	}

	.line-h {
		position: fixed;
		top: 88px;
		width: 100%;
		display: none;
	}
</style>